package com.zte.claa.inficombo.csa.app.service.gprscat1.mina;
/**
 * author:0283000106
 */
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zte.claa.inficombo.csa.app.config.GPRSCat1DevConnProps;
import com.zte.claa.inficombo.csa.app.service.gprscat1.bean.GPRSDevCommand;

public class GPRSDevConnSession {
	public static final short DEV_UNREG  = 0x01;
	public static final short DEV_REGED  = 0x02;
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private IoSession session = null;
	// 连接参数.	
	private GPRSCat1DevConnProps connProps;
	// 下行命令流水号.
	private AtomicInteger SNO = null;
	// 设备deveui.
	private String deveui = "";
	// 消息处理流程状态积
	private int procstat = DEV_UNREG;
	// 设备imei号
	private String imei;
	// 设备是否需要升级
	private boolean updatefinished = false;
		
	// 构建器.
	public GPRSDevConnSession(IoSession connSession, GPRSCat1DevConnProps connProps){
		this.session = connSession;
		this.connProps = connProps;
		this.SNO = new AtomicInteger(0);
	}
	
	/**
	 * 释放session和connector.
	 */
	public void stopSession() {
		if(this.session != null && !this.session.isClosing()){
			try{
				this.session.closeNow();
				this.session = null;
				logger.info("session close ok!");
			}catch(Exception ex){
				logger.error("Session close failed!", ex);
			}		
		}	
	}
	
	// 获取 SNO.
	public int getMessageSno(){
		int ret = this.SNO.incrementAndGet();
		if(ret > 65535){
			this.SNO = new AtomicInteger(0);
			ret = this.SNO.incrementAndGet();
		}
		return ret;
	}
	
	/**
	 * 下发命令。
	 * 
	 * @param cmd
	 * @throws Exception
	 */
	public WriteFuture sendCommand(GPRSDevCommand msg) throws Exception {
		if(session == null){
			throw new Exception("通信链路会话为空，网络不可达！");
		}
		return this.session.write(msg);  
	}

	public String getDeveui() {
		return deveui;
	}

	public void setDeveui(String deveui) {
		this.deveui = deveui;
	}	
    
	public IoSession getSession() {
		return session;
	}
	
	
	public long getSessionId() {
		return session.getId();
	}

	public int getProcstat() {
		return procstat;
	}

	public void setProcstat(int procstat) {
		this.procstat = procstat;
	}

	public String getImei() {
		return imei;
	}

	public void setImei(String imei) {
		this.imei = imei;
	}

	public boolean isUpdatefinished() {
		return updatefinished;
	}

	public void setUpdatefinished(boolean updatefinished) {
		this.updatefinished = updatefinished;
	}

	public GPRSCat1DevConnProps getConnProps() {
		return connProps;
	}

	public void setConnProps(GPRSCat1DevConnProps connProps) {
		this.connProps = connProps;
	}
	
}
